<template>
  <div class="fr purchase-box" :class="{'show':purvisible}"@mouseenter="shopboxEnter" @mouseleave="shopboxLeave" ref="head_search">
    <a class="shoplist" :class="{'show-shoplist':purvisible}" >
        <i class="iconfont el-icon-knife-shop_cart"></i>
        <span class="text">采购清单(<span class="yellow">{{totalNum <= 999 ? totalNum : '999+'}}</span>)</span>
    </a>
    <!-- 购物清单 -->
    <transition name="el-fade-in-linear" >
      <div class="purchasebox" ref="purchasebox" v-show="purvisible">
        <div class="purchase_item">
          <div :key="cartItem.id" v-for="(cartItem, cartIndex) in cartList.slice(0,1)" ref="shopcart" :name="cartItem.id">
            <div class="shop_title">购物车<span class="hori_line"></span></div>
            <section class="purchaselist">
              <div class="good_infos">
                <div class="skus_box_detail" v-for="(skuItem, skuIndex) in cartItem.productList" :key="skuIndex">
                  <div class="pro_img">
                    <img :src="prefixImg + skuItem.goodsImg" @error="catchErrorImage"/>
                    <span class="discount-tag" v-if="skuItem.activity">活动</span>
                  </div>
                  <div class="pro_name ellipsis pointer" @click="linkGoodsDetail(skuItem.goodsId, skuItem.activity)">
                    <span class="line15"><em v-if="skuItem.brandName">[{{skuItem.brandName}}]</em>{{skuItem.goodsName}}</span>
                    <span class="line15" v-show="skuItem.other">- {{skuItem.other}}</span><br>
                    <span>{{skuItem.productName}}</span>
                  </div>
                  <div class="pro_good_price">
                    <p class="pmt_price" v-if="skuItem.productPmtPrice">¥{{skuItem.productPmtPrice | floatPrices}}</p>
                    <p class="good_price" :class="{'old_price': skuItem.productPmtPrice}" >¥{{skuItem.productPrice | floatPrices}}</p>
                  </div>
                  <span class="good_amount">
                    <el-input-number class="input-num-self"
                      @keydown.110.native.prevent=""
                      v-model="skuItem.number"
                      :min="1"
                      :max="skuItem.stockLimit ? (skuItem.personalLimited ? skuItem.lastPersonalLimitNum : skuItem.stock) : 99999"
                      :step="skuItem.packingNum"
                      :ref="`pro_${skuIndex}`"
                      @change="changeProNum($event, cartIndex,skuIndex, skuItem)" >
                    </el-input-number>
                  </span>
                  <div class="pro_total_price">
                    ¥{{skuItem.productPmtPrice ? (skuItem.number * skuItem.productPmtPrice).toFixed(2) : (skuItem.number * skuItem.productPrice).toFixed(2)}}
                    <p class="prefer-price" v-if="parseFloat(skuItem.pmtAmount) > 0"> 已优惠¥{{skuItem.pmtAmount | floatPrices}}元
                      <el-tooltip  placement="bottom">
                        <span slot="content">已优惠商品{{skuItem.lockedNum}}件</span>
                        <em class="el-icon-info"></em>
                      </el-tooltip>
                    </p>
                  </div>
                  <span class="good_oprate el-icon-close" @click="deleteSku(cartIndex, skuIndex, skuItem.id)"></span>
                  <div class="disabled-mask" v-if="skuItem.inventoryStatus===3 || (skuItem.stockLimit && skuItem.stock === 0 ) || (skuItem.activity && isOverTime(skuItem.endTime))"></div>
                </div>
              </div>
            </section>
          </div>
          <!-- 底部合计金额 合计数目 -->
          <div class="total_box">
            <a class="empty_btn" @click="clearGoods(0)"><i style="padding-right: 2px;" class="el-icon-delete"></i>清空 </a>
            <!-- <span>共计{{totalNum}}件</span> -->
            <!-- <el-button type="primary" class="fr" @click="goBalance">去结算</el-button> -->
            <a class="fr go-balance" @click="goBalance">去结算</a>
            <span class="fr total_price">￥{{totalPrice}}</span>
            <span class="fr">合计:</span>
          </div>
        </div>
      </div>
    </transition>
  </div>

</template>

<script>
import {prefixImg} from '@/tool/index'
import {on, off, getCookie} from '@/config/mUntils'
import {Tabs, Button, InputNumber, TabPane, CarouselItem, Tooltip} from 'element-ui'
import {clearCart, changeProNumber, deleteCart} from '@/service/get-data'
import {mapState, mapActions} from 'vuex'
import _ from 'lodash'
export default {
  name: 'purchase',
  components: {
    elTabs: Tabs,
    elButton: Button,
    elInputNumber: InputNumber,
    elTabPane: TabPane,
    elCarouselItem: CarouselItem,
    elTooltip: Tooltip
  },
  data () {
    return {
      purvisible: false,
      activeTabsValue: '', // 显示的清单name值
      tabIndex: 2,
      totalNum: 0, // 当前清单商品的数量
      totalPrice: 0.00, // 当前清单商品的总额
      cartList: []
    }
  },
  computed: {
    ...mapState({
      // 购物车的id
      shopcartId: state => state.shopcart.shopCartId,
      cartLists: state => state.shopcart.cartlist,
      nowDiscount: state => state.user.discount
      // Exam: state => state.user.isExam
    }),
    prefixImg () {
      return prefixImg
    },
    Token () {
      return getCookie('Token')
    },
    Exam () {
      return parseInt(getCookie('Exam'))
    }
  },
  methods: {
    ...mapActions(['fetchCartList']),
    catchErrorImage (e) {
      e.target.src = require('img/newload.png')
    },
    isOverTime (timeEnd) {
      if (!timeEnd) return
      let now = new Date()
      let getTime = now.getTime()
      let endTime = new Date(timeEnd.replace(/-/g, '/')).getTime()
      // 过期
      if (getTime >= endTime) {
        return true
      } else {
        return false
      }
    },
    // propsd的购物车列表 赋值给data数据
    _initValueCart () {
      this.cartList = JSON.parse(JSON.stringify(this.cartLists))
    },
    // 货品数量的修改 changeProNumber
    changeProNum (value, cartIndex, skuIndex, objitem) {
      this.debouncePro(value, cartIndex, skuIndex, objitem)
    },
    // 防抖 添加货物
    debounceInputAmount () {
      this.debouncePro = _.debounce(async function (value, cartIndex, skuIndex, objitem) {
        console.log(value)
        let step = objitem.packingNum
        // 输入框里删除的情况下为undefined，处理方式为改为最低数量step
        if (value === undefined) {
          this.cartList[cartIndex]['productList'][skuIndex]['number'] = step
          value = step
        }
        // 如果不存在id请求购物车
        if (!this.shopcartId) {
          this.fetchCartList()
          this.shopcartId = this.$store.state.shopcart.shopCartId
        }
        // 计算倍数
        let lastNum = value % step
        if (lastNum !== 0) {
          this.$message({
            message: `此商品盒装数${step}`
          })
        }
        let leftNum = lastNum === 0 ? value : value - lastNum + step
        let _arr = this.cartList[cartIndex]
        let curObj = _arr['productList'][skuIndex]
        // 个人限购 商品不限购
        if (curObj.personalLimited) {
          if (curObj.stockLimit && leftNum > curObj.stock) {
            leftNum = curObj.stock
            this.$message(`您的选购数量已达库存数量`)
          } else if (curObj.lastPersonalLimitNum === 0 || leftNum > curObj.lastPersonalLimitNum) {
            leftNum = curObj.lastPersonalLimitNum
            this.$message(`抱歉,此商品限购期间每人限购${curObj.personalLimitNum}件,您已达此商品的添加上限`)
          } // 商品限购
        } else if (curObj.stockLimit && leftNum > curObj.stock) {
          this.$message('您的选购数量已达库存数量')
          leftNum = curObj.stock
        }
        _arr['productList'][skuIndex]['number'] = leftNum
        this.$set(this.cartList, cartIndex, _arr)
        this.$nextTick(() => {
          // this.$refs[`pro_${skuIndex}`][0].$refs.input.setCurrentValue(leftNum)
          this.$refs[`pro_${skuIndex}`][0].setCurrentValue(leftNum)
        })
        let res = await changeProNumber(this.shopcartId, '', objitem.id, leftNum, 1)
        if (res.data.resultCode && res.data.resultCode === 2000) {
          this.fetchCartList()
        } else { // 数量超限
          this.$message.error(res.data.resultMsg || '网络错误')
        }
      }, 300, {leading: true, trailing: false})
    },
    // 删除商品
    async deleteSku (cartIndexT, productIndexT, id) {
      let res = await deleteCart(id)
      if (res.data.resultCode && res.data.resultCode === 2000) {
        this.fetchCartList()
      }

      this.cartList.map((cartItem, cartIndex) => {
        cartItem.productList.map((productItem, productIndex) => {
          if (cartIndexT === cartIndex) {
            if (productIndex === productIndexT) {
              cartItem.productList.splice(productIndexT, 1)
              let resultSku = cartItem.productList
              this.$set(this.cartList, this.cartList[cartIndex]['productList'], resultSku)
            }
          }
        })
      })
    },
    // 清空购物车
    async clearGoods (index) {
      this.$confirm('是否要清空购物车?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then((res, rej) => {
        return clearCart(this.shopcartId)
      }).then((res) => {
        if (res.data.resultCode === 2000) {
          let _cart = this.cartList[index]
          _cart['productList'] = ''
          this.purvisible = false
          this.$set(this.cartList, index, _cart)
          // let route = this.$route
        } else {
          this.$message({
            message: res.data.resultMsg
          })
        }
      }).catch(() => {
        this.purvisible = true
      })
    },
    // 去结算
    goBalance () {
      this.purvisible = false
      this.$router.push({name: 'ShopCart'})
    },
    shopboxEnter () {
      if (this.Token && this.Exam === 1) {
        this.purvisible = !this.purvisible
      } else if (this.Token) {
        if (this.Exam === 3) {
          this.$store.commit('EXAMNODO', true)
          return false
        } else if (this.Exam === 2) {
          this.$store.commit('EXAMFAIL', true)
          return false
        } else {
          this.$message.error('您的企业信息还在审核中,商品不能加入购物车,我们尽快给您审核.')
          return false
        }
      } else {
        this.$confirm('此操作需要登录,是否前去登录', '提示').then(() => {
          this.$router.push({name: 'Login', query: { redirect: this.$route.fullPath }})
        }).catch(() => {
        })
      }
    },
    shopboxLeave () {
      this.purvisible = false
    },
    handleBodyClick (e) {
      let headsearch = this.$refs['head_search']
      if (headsearch.contains(e.target)) {
        return
      }
      this.purvisible = false
    },
    // 跳转到商品详情页
    linkGoodsDetail (id, active) {
      let routeData
      routeData = this.$router.resolve({name: 'productDetail', params: {commodityID: id}})
      window.open(routeData.href, '_blank')
    }
  },
  mounted () {
    on(document, 'click', this.handleBodyClick)
    this._initValueCart()
    this.debounceInputAmount()
  },
  watch: {
    cartLists (newVal) {
      this._initValueCart()
    },
    cartList: {
      handler (newVal, oldVal) {
        if (newVal.length > 0) {
          newVal = newVal[0]
          let totalNum = 0
          let totalPrice = 0
          if (newVal['productList'].length > 0) {
            newVal['productList'].map((productItem, productIndex) => {
              let pmtAmount = productItem.pmtAmount > 0 ? productItem.pmtAmount : 0
              totalNum += parseInt(productItem.number)
              totalPrice += parseFloat(productItem.number * productItem.productPrice - pmtAmount)
            })
          }
          this.totalNum = totalNum
          this.$store.commit('SHOPCARTNUM', this.totalNum)
          this.totalPrice = totalPrice.toFixed(2)
        }
      },
      deep: true
    }
  },
  destroyed () {
    // const reference = this.refs.purchasebox
    off(document, 'click', this.handleBodyClick)
  }
}
</script>

<style lang="scss" scoped>
  $font_color:#474747;
  $height:50px;
  $yellow_color:#FFCC00;
  $ora_color: #EF6600;
  .line15{line-height: 15px;}
  .purchase-box{
    position: relative;
    z-index: 1500;
    margin-top: 5px;
    margin-left: 20px;
    &.show{
      filter: drop-shadow(0 5px 2px rgba(0,0,0,.5));
    }
  }
  //  计数器
  .input-num-self{
    width: 138px;
    vertical-align: middle;
  }
  .shop_title{
    position: relative;
    border-radius: 4px;
    font-size: 18px;
    border-bottom: 1px solid #f4f4f4;
    color: #767676;
    padding: 10px 25px;
    .hori_line{
      position: absolute;
      bottom: 0;
      left: -5px;
      background: #333333;
      display:inline-block;
      height: 2px;
      width:120px;
    }
  }
   .empty_btn{
      display: inline-block;
      margin-top: 10px;
      font-size: 14px;
      cursor: pointer;
    }
.shoplist{
    font-family: PingFangSC-Regular, Microsoft YaHei;
    position: relative;
    width: 150px;
    height: 50px;
    box-sizing: border-box;
    display: inline-block;
    cursor: pointer;
    border: 1px solid #999999;
    border-radius: 4px;
    color: #666;
    text-align: center;
    padding: 17px 0 13px;
    font-size:0;
    z-index: 55;
    background: #fff;
    .iconfont{
      font-weight: 600;
      vertical-align: middle;
    }
    .text{
      display: inline-block;
      vertical-align: middle;
      text-align: center;
      font-size: 16px;
    }
  }
    .show-shoplist{
    border-bottom: none;
    border-bottom-right-radius: 0;
    border-bottom-left-radius: 0;
  }
  .clear_shop{
    border-top: 1px solid #f4f4f4;
    border-bottom: 1px solid #f4f4f4;
    padding-left: 10px
  }
  .yellow{
    color: $ora_color;
  }
.purchase_item{
    position: relative;
    height: 100%;
    overflow: hidden;
    border-radius: 0 0 6px 6px;
    background: #fff;
    font-size: 14px;
    }
  .purchasebox{
    position: absolute;
    top: 49px;
    right: 0;
    z-index: 50;
    line-height: 40px;
    width: 848px;
    //height: 350px;
    background: #ffffff;
    // box-shadow: 0 2px 5px 0 rgba(0,0,0,0.05);
    border-radius: 6px 0 6px 6px;
    border: 1px solid #ececec;
  }
  .el-tabs--card > .el-tabs__header .el-tabs__nav{
    border: none!important;
  }
  .good_infos{
    width: 100%;
    display: table;
  }
  .spu_img{
    width: 8%;
    display: table-cell;
    vertical-align: top;
    & > img {
      width: 70%;
    }
  }
  .spu_name{
    width: 125px;
    margin-top: 10px;
    //display: table-cell;
    vertical-align: top;
    font-size: 14px;
    line-height: 20px;
    color: #474747;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 3;
    overflow: hidden;
  }
  .skus_box{
    width: 70%;
    display: table-cell;
    vertical-align: top;
    .skus_box_detail{
      margin-bottom: 10px
    }
  }

  .skus_box_detail{
    position: relative;
    border-bottom: 1px solid #ececec;
    padding: 15px 0;
    &:last-child{
      border-bottom:none;
    }
    span{
      display: inline-block;
    }
    .pro_img{
      position: relative;
      display: inline-block;
      width: 65px;
      vertical-align: middle;
      height: 65px;
      margin: 0 30px;
      & > img{
        width: 100%;
        height:100%;
      }
    }
    .pro_total_price{
      display: inline-block;
      vertical-align: middle;
      line-height: 25px;
      width: 15%;
      text-align: center;
      font-size: 16px;
    }
    .prefer-price{
      color: #474747;
      font-size: 12px;
    }
    .pro_name{
      width: 27%;
      display: inline-block;
      vertical-align: middle;
      padding: 10px 0 10px 0;
      line-height: 2;
      font-size: 16px;
      color: #474747;
      .first{
        padding-right: 13px;
      }
    }
    .good_amount{
      text-align: center;
      width: 20%;
    }
  }
  .disabled-mask {
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    background: rgba(247, 247, 247, 0.5);
    z-index: 88;
  }
  .pro_good_price{
    display: inline-block;
    width: 12%;
    text-align:center;
    color: #666;
    font-size: 16px;
    vertical-align: middle;
    .pmt_price{
      line-height: 30px;
      color: #ff0000;
    }
    .old_price{
      line-height: 20px;
      color: #999;
      text-decoration: line-through;
      font-size: 12px;
    }
  }
  .good_oprate{
    position: relative;
    display: inline-block;
    width: 8%;
    text-align: left;
    cursor: pointer;
    z-index: 90;
    &:hover{
      color:#FFCC00
    }
  }
  .purchaselist{
    // height: 220px;scroll
    max-height: 384px;
    margin-bottom: 80px;
    overflow-y: auto;
  }
  .total_box{
    position: absolute;
    box-sizing: border-box;
    width: 100%;
    padding: 10px 12px 10px 20px;
    bottom:0;
    left: 0;
    right: 0;
    background: #F4F4F4;
    z-index:2;
    .total_price{
      padding-right: 10px;
      color: #666;
      font-size: 28px;
    }
    span{
      font-size: 14px;
      color: #666666;
      margin-top: 10px;
    }
    .go-balance{
      width:150px;
      height:60px;
      cursor: pointer;
      text-align: center;
      line-height: 60px;
      font-size: 20px;
      color: #444444;
      letter-spacing: 1.12px;
      background: #FFCC00;
      border-radius: 4px;
    }
  }
</style>
